/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.wcalendar.business.security.boundary;

import it.polimi.wcalendar.business.security.entity.Group;
import it.polimi.wcalendar.business.security.entity.User;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;

import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author gugu
 */
@Stateless
public class UserManager {

    @PersistenceContext
    EntityManager em;

    @Inject
    Principal principal;

    public List getAll() {
        Query createNamedQuery = em.createNamedQuery("User.findAll");
        List list = createNamedQuery.getResultList();
        return list;
    }

    public void save(User user) {
        user.setGroupname(Group.USERS);
        em.persist(user);
    }

    public User loadByNickname(String nickname) {
        return em.find(User.class, nickname);
    }

    public void unregister() {
        em.remove(getLoggedUser());
    }

    public User getLoggedUser() {
        return em.find(User.class, principal.getName());
    }

    public ArrayList<String> getAllUsernames(String creatorUsername) {
        Query createNamedQuery = em.createNamedQuery("User.findAll");
        List list = createNamedQuery.getResultList();
        ArrayList<String> allUsernames = new ArrayList<>();
        for (Object elem : list) {
            User user = (User) elem;
            if (user.getNickname() != creatorUsername) {
                allUsernames.add(user.getNickname());
            }
        }
        return allUsernames;
    }
}
